package com.ruoyi.procurement.service.impl;

import com.ruoyi.audit.domain.Audit;
import com.ruoyi.audit.mapper.AuditMapper;
import com.ruoyi.audit.mapper.InventoryAmountMapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.WXShiroUtils;
import com.ruoyi.company.domain.CompanyOther;
import com.ruoyi.company.mapper.CompanyOtherMapper;
import com.ruoyi.enterStock.mapper.EnterstockMapper;
import com.ruoyi.information.domain.Information;
import com.ruoyi.information.mapper.InformationMapper;
import com.ruoyi.manufacturer.domain.DjManufacturer;
import com.ruoyi.manufacturer.mapper.DjManufacturerMapper;
import com.ruoyi.procurement.design.ProcurementStateHandlerFactory;
import com.ruoyi.procurement.domain.ProcurementModel;
import com.ruoyi.procurement.domain.ProcurementOrder;
import com.ruoyi.procurement.mapper.ProcurementOrderMapper;
import com.ruoyi.procurement.service.ProcurementServer;
import com.ruoyi.product.domain.AICode;
import com.ruoyi.product.domain.PictureMemory;
import com.ruoyi.product.domain.Product;
import com.ruoyi.product.domain.ProductModel;
import com.ruoyi.product.mapper.AICodeMapper;
import com.ruoyi.product.mapper.ProductMapper;
import com.ruoyi.productProof.domain.ProductProof;
import com.ruoyi.productProof.mapper.ProductProofMapper;
import com.ruoyi.purchase.domain.PurchaseModel;
import com.ruoyi.purchase.domain.PurchaseOrder;
import com.ruoyi.purchase.mapper.PurchaseOrderMapper;
import com.ruoyi.sale.domain.SaleGoodsModel;
import com.ruoyi.sale.domain.SaleGoodsOrder;
import com.ruoyi.sale.mapper.SaleGoodsMapper;
import com.ruoyi.warehousing.domain.Warehousing;
import com.ruoyi.warehousing.domain.WarehousingRecords;
import com.ruoyi.warehousing.mapper.WarehousingMapper;
import com.ruoyi.warehousing.mapper.WarehousingRecordsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.security.Security;
import java.util.*;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import java.util.stream.Collectors;

@Service
public class ProcurementOrderServiceImpl implements ProcurementServer {

    @Autowired
    SaleGoodsMapper saleGoodsMapper;

    @Autowired
    ProductMapper productMapper;

    @Autowired
    ProductProofMapper proofMapper;

    @Autowired
    AICodeMapper aiCodeMapper;

    @Autowired
    DjManufacturerMapper djManufacturerMapper;

    @Autowired
    PurchaseOrderMapper purchaseOrderMapper;

    @Autowired
    EnterstockMapper enterstockMapper;

    @Autowired
    private AuditMapper auditMapper;

    @Autowired
    private ProcurementOrderMapper procurementOrderMapper;

    @Autowired
    private InformationMapper informationMapper;

    @Autowired
    private WarehousingMapper warehousingMapper;

    @Autowired
    private WarehousingRecordsMapper warehousingRecordsMapper;

    @Autowired
    private CompanyOtherMapper iCompanyOtherMapper;

    /**
     * 查询采购入库订单
     *
     * @param procurementOrder 查询条件
     * @return 结果集
     */
    @Override
    public List<ProcurementOrder> selectProcurementList(ProcurementOrder procurementOrder) {
        return procurementOrderMapper.selectProcurementList(procurementOrder);
    }

    /**
     * 查询订单入库信息 已同意
     *
     * @param procurementOrder 查询条件
     * @return 结果
     */
    @Override
    public List<ProcurementOrder> selectProcurementLists(ProcurementOrder procurementOrder) {
        return procurementOrderMapper.selectProcurementLists(procurementOrder);
    }

    /**
     * 插入 入库订单信息
     *
     * @param procurementOrder 入库订单信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertProcurementOrder(ProcurementOrder procurementOrder) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        //插入入库订单
        Long deptId = sysUser.getCompanyId();
        procurementOrder.setDeptId(deptId);
        Long saleGoodsId = procurementOrder.getProcurementModelList().get(0).getSaleGoodsId();
        procurementOrder.setSaleGoodsId(saleGoodsId);
        procurementOrder.setCreateBy(sysUser.getNickName());
        procurementOrderMapper.insertProcurementOrder(procurementOrder);
        Product product1 = new Product();
        Long supplierId = procurementOrder.getSupplierId();
        if (procurementOrder.getProcurementModelList() != null && saleGoodsId != null) {
            List<ProcurementModel> procurementModelList1 = procurementOrder.getProcurementModelList();
            //循环入库子表数据，判断本公司是否有该产品型号
            for (ProcurementModel procurementModel : procurementModelList1) {
                //通过产品型号为一码查询产品信息 集合
                String modelCode = procurementModel.getModelCode();
                ProductModel productModelList = productMapper.selectProductByModelCode(supplierId, modelCode);
                if (productMapper.selectProductByModelCode(deptId, modelCode) != null) {
                    ProductModel productModel = productMapper.selectProductByModelCode(deptId, modelCode);
                    Long productId = productModel.getProductId();
                    procurementModel.setProductId(productId);
                    continue;
                } else {
                    Long modelNo = procurementModel.getModelNo();
                    Long productId1 = procurementModel.getProductId();
                    product1.setDeptId(sysUser.getDeptId());
                    product1.setProductId(productId1);
                    Product product = productMapper.selectProductById(product1);
                    Map<String, Object> map = new HashMap<>();
                    map.put("medicalNumber", procurementModel.getMedicalNumber());
                    map.put("deptId", deptId);
                    //查询医疗器械注册证，
                    Product productProof = productMapper.selectProductProof(product1);
                    if (productProof != null) {
                        ProductModel productModel = productMapper.selectProductByModelCode(deptId, modelCode);
                        if (productModel == null) {
                            ProductModel productModels = productMapper.selectProductByModelCode(supplierId, modelCode);
                            //查询生产商
                            DjManufacturer djManufacturer = djManufacturerMapper.selectDjManufacturerById(productModels.getManufacturerId());
                            djManufacturer.setCompanyId(deptId);
                            djManufacturer.setManufacturerId(null);
                            int i = djManufacturerMapper.insertDjManufacturer(djManufacturer);
                            productModels.setManufacturerId(djManufacturer.getManufacturerId());
                            productModels.setDeptId(deptId);
                            productModels.setProductId(productProof.getProductId());
                            productMapper.insertProductModel(productModels);
                            //查询图片集合
                            List<PictureMemory> pictureMemoryList = productMapper.selectProductImg(modelNo);
                            //循环赋值将产品规格中图片信息
                            if (pictureMemoryList.size() != 0) {
                                for (PictureMemory pictureMemory : pictureMemoryList) {
                                    pictureMemory.setPictureNo(null);
                                    pictureMemory.setModelNo(productModels.getModelNo());
                                }
                                productMapper.insertPictureMemory(pictureMemoryList);
                            }
                        }
                        procurementModel.setProductId(productProof.getProductId());
                        procurementModel.setDeptId(deptId);
                    } else {
                        AICode aiCode = new AICode();
                        aiCode.setDeptId(supplierId);
                        aiCode.setProductId(productId1);
                        //供应商的产品条形码信息
                        List<AICode> aiCodes = aiCodeMapper.selectAICode(aiCode);
                        aiCode.setDeptId(deptId);
                        //本公司下的条形码信息
                        List<AICode> aiCodes1 = aiCodeMapper.selectAICode(aiCode);

                        product.setDeptId(deptId);
//                      if (productMapper.selectProductList(product) == null) {
                        product.setProductId(productId1);
                        productMapper.insertProduct(product);
                        Long productId = product.getProductId();

                        map.put("deptId", supplierId);
                    /*    ProductProof productProof1 = proofMapper.selectProductProofByMap(map);
                        if (productProof1 != null) {
                            productProof1.setDeptId(deptId);
                            productProof1.setProductProofId(null);
                            productProof1.setProductId(productId);
                            proofMapper.insertProductProof(productProof1);
                        }*/

                        //将供应商的产品的条形码信息带到本公司下
                        if (aiCodes1.size() != 0) {
                            if (aiCodes.size() != 0) {
                                for (AICode code : aiCodes) {
                                    code.setDeptId(deptId);
                                    code.setProductId(product.getProductId());
                                }
                                aiCodeMapper.updateAICodeList(aiCodes);
                            }
                        } else {
                            if (aiCodes.size() != 0) {
                                for (AICode code : aiCodes) {
                                    code.setDeptId(deptId);
                                    code.setProductId(product.getProductId());
                                }
                                aiCodeMapper.insertAICodeList(aiCodes);
                            }
                        }
                        if (productModelList != null) {
                            DjManufacturer djManufacturer = djManufacturerMapper.selectDjManufacturerById(productModelList.getManufacturerId());
                            djManufacturer.setCompanyId(deptId);
                            int i = djManufacturerMapper.updateDjManufacturer(djManufacturer);
                            productModelList.setManufacturerId(djManufacturer.getManufacturerId());

                            //查询图片集合
                            List<PictureMemory> pictureMemoryList = productMapper.selectProductImg(productModelList.getModelNo());
                            //插入产品规格信息
                            productModelList.setProductId(productId);
                            productModelList.setDeptId(deptId);
                            productMapper.insertProductModel(productModelList);
                            procurementModel.setProductId(productId);
                            //循环赋值将产品规格中图片信息
                            if (pictureMemoryList.size() != 0) {
                                for (PictureMemory pictureMemory : pictureMemoryList) {
                                    pictureMemory.setPictureNo(null);
                                    pictureMemory.setModelNo(productModelList.getModelNo());
                                }
                                productMapper.insertPictureMemory(pictureMemoryList);
                            }
                        }
                    }
                }
            }
        }

        //插入入库详细信息订单
        procurementOrderMapper.insertProcurementModelList(procurementOrder);
        //判断是否有该批次产品的产品资料 有修改，没有插入
        List<ProcurementModel> procurementModelList = procurementOrder.getProcurementModelList();
        for (ProcurementModel procurementModel : procurementModelList) {
            Information information = new Information();
            information.setBatch(procurementModel.getBatch());
            information.setDeptId(deptId);
            information.setModelCode(procurementModel.getModelCode());
            information.setFactoryInspectionName(procurementModel.getFactoryInspectionName());
            information.setFactoryInspectionAddress(procurementModel.getFactoryInspectionAddress());
            information.setCustomsName(procurementModel.getCustomsName());
            if (procurementModel.getCustomsAddress() != null && !procurementModel.getCustomsAddress().isEmpty()) {
                information.setCustomsAddress(procurementModel.getCustomsAddress().replaceAll("/profile/upload", ""));
            }
            information.setCommodityName(procurementModel.getCommodityName());
            information.setCommodityAddress(procurementModel.getCommodityAddress());
            information.setDisinfectName(procurementModel.getDisinfectName());
            information.setDisinfectAddress(procurementModel.getDisinfectAddress());
            information.setNucleicAcidName(procurementModel.getNucleicAcidName());
            information.setNucleicAcidAddress(procurementModel.getNucleicAcidAddress());
            information.setCreateBy(sysUser.getNickName());
            information.setUpdateBy(sysUser.getNickName());

            //判断是否拥有产品资料 有修改，否则插入
            if (informationMapper.selectInformationList(information).size() != 0) {
                informationMapper.updateInformation(information);
            } else {
                informationMapper.insertInformationCount(information);
            }
        }

        SaleGoodsOrder saleGoodsOrder = new SaleGoodsOrder();
        saleGoodsOrder.setSaleGoodsId(saleGoodsId);
        saleGoodsOrder.setIsWarehousingOrder(1);

        //修改销货订单状态
        if (saleGoodsId != null) {
            int a = saleGoodsMapper.updateSaleGoodsOrder(saleGoodsOrder);
        }

        //添加审核订单
        Audit audit = new Audit();
        audit.setOrderId(procurementOrder.getProcurementWarehousingId());
        audit.setCompanyId(sysUser.getCompanyId());
        audit.setOrderType("2");
        audit.setAuditStatus("0");
        audit.setUserId(procurementOrder.getUserId());
        audit.setSupplierId(procurementOrder.getSupplierId());
        audit.setTaxAmount(procurementOrder.getTaxAmount());
        //订单编号
        audit.setOrderNum(procurementOrder.getProcurementWarehousingName());
        auditMapper.insertAudit(audit);

        return 1;
    }

    /**
     * 删除入库订单
     *
     * @param procurementWarehousingId 入库订单主键
     */
    @Override
    @Transactional
    public void deleteProcurementModel(Long procurementWarehousingId) {
        //查询采购入库订单是否为空
        if (procurementOrderMapper.selectProcurementWarehousingIdList(procurementWarehousingId).size() != 0) {
            procurementOrderMapper.deleteProcurementModel(procurementOrderMapper.selectProcurementWarehousingIdList(procurementWarehousingId));
        }
        //删除审核订单数据
        Map<String, Object> map = new HashMap<>();
        map.put("orderId", procurementWarehousingId);
        map.put("companyId", SecurityUtils.getLoginUser().getUser().getCompanyId());
        map.put("orderType", "2");
        auditMapper.deleteAuditWith(map);
        ProcurementOrder procurementOrder = procurementOrderMapper.selectProcurementById(procurementWarehousingId);
        Long saleGoodsId = procurementOrder.getSaleGoodsId();

        SaleGoodsOrder saleGoodsOrder = new SaleGoodsOrder();
        saleGoodsOrder.setSaleGoodsId(saleGoodsId);
        saleGoodsOrder.setSaleGoodsStatus("1");
        saleGoodsOrder.setIsWarehousingOrder(0);
        //判断是否为销货单入库，是则修改销货单是否生成入库订单
        if (saleGoodsId != null) {
            saleGoodsMapper.updateSaleGoodsOrder(saleGoodsOrder);
        }
        procurementOrderMapper.deleteProcurementOrder(procurementWarehousingId);

    }

    /**
     * 根据入库订单主键查询
     *
     * @param procurementWarehousingId 入库订单主键
     * @return 结果
     */
    @Override
    public ProcurementOrder selectProcurementById(Long procurementWarehousingId) {
        return procurementOrderMapper.selectProcurementById(procurementWarehousingId);
    }

    /**
     * 根据入库订单主键查询入库型号信息
     *
     * @param procurementWarehousingId 入库订单主键
     * @return 结果
     */
    @Override
    public List<ProcurementModel> selectProcurementModelById(Long procurementWarehousingId) {
        return procurementOrderMapper.selectProcurementModelById(procurementWarehousingId);
    }

    /**
     * 查询入库信息
     *
     * @param procurementOrder 查询条件
     * @return 结果
     */
    @Override
    public ProcurementOrder selectProcurementBy(ProcurementOrder procurementOrder) {
        return procurementOrderMapper.selectProcurementBy(procurementOrder);
    }

    /**
     * 修改入库信息
     *
     * @param procurementOrder 查询条件
     * @return 结果
     */
    @Override
    @Transactional
    public int updateProcurementOrder(ProcurementOrder procurementOrder) {

        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        //通过入库订单主键 查询所有入库详情主键
        Long procurementWarehousingId = procurementOrder.getProcurementWarehousingId();
        List<Long> longs = procurementOrderMapper.selectProcurementWarehousingIdList(procurementWarehousingId);
        //添加审核订单
        Audit audit = new Audit();
        audit.setOrderId(procurementOrder.getProcurementWarehousingId());
        audit.setCompanyId(sysUser.getCompanyId());
        audit.setOrderType("2");
        Audit audit1 = auditMapper.selectAudit(audit);
        if (audit1.getAuditStatus().equals("1")) {

            audit.setUserId(procurementOrder.getUserId());
            audit.setSupplierId(procurementOrder.getSupplierId());
            audit.setTaxAmount(procurementOrder.getTaxAmount());
            //订单编号
            audit.setOrderNum(procurementOrder.getProcurementWarehousingName());
            auditMapper.updateAuditOther(audit);
        } else {

            audit.setAuditStatus("0");
            audit.setUserId(procurementOrder.getUserId());
            audit.setSupplierId(procurementOrder.getSupplierId());
            audit.setTaxAmount(procurementOrder.getTaxAmount());
            //订单编号
            audit.setOrderNum(procurementOrder.getProcurementWarehousingName());
            auditMapper.updateAuditOther(audit);
        }


        //判断入库规格详情是否为空
        if (procurementOrder.getProcurementModelList() != null) {
            ArrayList<Long> longs1 = new ArrayList<>();
            List<ProcurementModel> procurementModelList = procurementOrder.getProcurementModelList();
            for (ProcurementModel procurementModel : procurementModelList) {
                if (procurementModel.getProcurementWarehousingNo() != null) {
                    Long procurementWarehousingNo = procurementModel.getProcurementWarehousingNo();
                    longs1.add(procurementWarehousingNo);
                    procurementOrderMapper.updateProcurementModel(procurementModel);
                } else {
                    procurementModel.setProcurementWarehousingId(procurementOrder.getProcurementWarehousingId());
                    procurementModel.setDeptId(sysUser.getCompanyId());
                    procurementOrderMapper.insertProcurementModel(procurementModel);
                }
                //对产品资料进行判断
                Information information = new Information();
                information.setBatch(procurementModel.getBatch());
                information.setModelCode(procurementModel.getModelCode());
                information.setDeptId(procurementModel.getDeptId());
                information.setFactoryInspectionName(procurementModel.getFactoryInspectionName());
                information.setFactoryInspectionAddress(procurementModel.getFactoryInspectionAddress());
                information.setCustomsName(procurementModel.getCustomsName());
                information.setCustomsAddress(procurementModel.getCustomsAddress());
                information.setCommodityName(procurementModel.getCommodityName());
                information.setCommodityAddress(procurementModel.getCommodityAddress());
                information.setDisinfectName(procurementModel.getDisinfectName());
                information.setDisinfectAddress(procurementModel.getDisinfectAddress());
                information.setNucleicAcidName(procurementModel.getNucleicAcidName());
                information.setNucleicAcidAddress(procurementModel.getNucleicAcidAddress());
                information.setUpdateBy(sysUser.getNickName());

                //查询一家公司是否拥有相同型号批次的资料
                if (informationMapper.selectInformationList(information).size() != 0) {
                    informationMapper.updateInformation(information);
                } else {
                    informationMapper.insertInformationCount(information);
                }


            }
            if (longs1.size() != 0 && longs != null) {
                //数组中剩余的数就是需要删除的数据
                boolean b = longs.removeAll(longs1);
                if (longs.size() != 0) {
                    procurementOrderMapper.deleteProcurementModel(longs);
                }
            }
        } else {
            if (longs != null) {
                procurementOrderMapper.deleteProcurementModel(longs);
            }
        }
        return procurementOrderMapper.updateProcurementOrder(procurementOrder);
    }

    /**
     * 用于统计数据计算库存
     *
     * @param procurementOrder 条件
     */
    @Override
    @Transactional
    public void calculation(ProcurementOrder procurementOrder) {

        SysUser sysUser = SecurityUtils.getLoginUser().getUser();

        //根据主键查询数据，判断是否含有产品规格型号子集
        // todo 2选1,如果是使用销售审核去审核单子的时候选1,如果是新版审核使用2
        // ProcurementOrder procurementOrder1 = procurementOrderMapper.selectProcurementBy(procurementOrder);
        ProcurementOrder procurementOrder1 = procurementOrder; // procurementOrderMapper.selectProcurementBy(procurementOrder);

        if (procurementOrder1.getProcurementModelList() != null) {
            //循环插入库存数据
            List<ProcurementModel> procurementModelList = procurementOrder1.getProcurementModelList();
            WarehousingRecords warehousingRecords = new WarehousingRecords();
            for (ProcurementModel procurementModel : procurementModelList) {
                Long deptId = procurementModel.getDeptId();
                String productType = procurementModel.getProductType();
                Long productId = procurementModel.getProductId();
                String batch = procurementModel.getBatch();
                Long allNum = procurementModel.getAllNum();
                int warehousingAmount = procurementModel.getWarehousingAmount();
                int czNum = new Long(allNum).intValue();

                int purchaseNum = procurementModel.getPurchaseNum();
                String medicalNumber = procurementModel.getMedicalNumber();
                Date medicalEndTime = procurementModel.getMedicalEndTime();
                Date effectiveDate = procurementModel.getEffectiveDate();
                Date productionDate = procurementModel.getProductionDate();
                Long supplierId = procurementOrder1.getSupplierId();
                //创建新的存储对象，存入库存
                Warehousing warehousing = new Warehousing();

                warehousing.setBatch(batch);
                warehousing.setDeptId(deptId);
                warehousing.setProductId(productId);
                warehousing.setSelectId(productId);
                warehousing.setProductType(productType);
                //warehousing.setWarehousingNum(warehousingAmount);
                warehousing.setAmount(allNum);
                warehousing.setMedicalNumber(medicalNumber);
                warehousing.setEffectiveDate(effectiveDate);
                warehousing.setMedicalEndTime(medicalEndTime);
                warehousing.setProductionDate(productionDate);
                Warehousing warehousing1 = warehousingMapper.selectWarehousing(warehousing);

                //存储本次操作的数量
                warehousingRecords.setInventoryNum(warehousingAmount);
                warehousingRecords.setAllnum(allNum.intValue());
                //判断是否拥有该公司该产品该型号名称的库存记录
                if (warehousing1 == null) {
                    warehousingMapper.insertWarehousing(warehousing);
                } else {
                    Long warehousingNum = warehousing1.getAmount();
                    allNum += warehousingNum;
                    // warehousing.setWarehousingNum(warehousingAmount);
                    warehousing.setAmount(allNum);
                    warehousing.setWarehousingId(warehousing1.getWarehousingId());
                    warehousing.setUpdateBy(sysUser.getNickName());
                    warehousingMapper.updateWarehousing(warehousing);
                }
                Long warehousingId = warehousing.getWarehousingId();
                warehousingRecords.setWarehousingId(warehousingId);
                warehousingRecords.setOrderNum(procurementOrder1.getProcurementWarehousingName());
                warehousingRecords.setSupplierId(supplierId);
                warehousingRecords.setInventoryStatus("0");
                // 设置入库还是出库
                warehousingRecords.setInventoryStatus(procurementOrder1.getProcurementStatus().equals("0") ? "1" : "0");
                warehousingRecords.setCreateBy(sysUser.getNickName());
                warehousingRecordsMapper.insertWarehousingRecords(warehousingRecords);
            }

            //是否是 销货单入库 是的话 判断销货单是否 是选择了采购订单model
            if (procurementOrder1.getSaleGoodsId() != null) {
                //改变采购订单的 入库数量
                HashMap hashMap = new HashMap();
                hashMap.put("saleGoodsId", procurementOrder1.getSaleGoodsId());
                SaleGoodsOrder saleGoodsOrder = saleGoodsMapper.selectSaleGoodsById(hashMap);
                //判断该订单是否是选择了采购单
                boolean flag = false;
                for (int i = 0; i < saleGoodsOrder.getSaleGoodsModels().size(); i++) {
                    SaleGoodsModel saleGoodsModel = saleGoodsOrder.getSaleGoodsModels().get(i);
                    if (saleGoodsModel.getPurchaseModelId() != null) {
                        flag = true;
                    }
                }

                if (flag) {
                    ArrayList<Long> salegoodsModelIds = new ArrayList<>();
                    for (int i = 0; i < procurementOrder1.getProcurementModelList().size(); i++) {
                        salegoodsModelIds.add(procurementOrder1.getProcurementModelList().get(i).getSaleGoodsModelId());
                    }

                    List<PurchaseModel> models = saleGoodsMapper.selectProcurementAfterOutNum(salegoodsModelIds);
                    for (int i = 0; i < models.size(); i++) {
                        models.get(i).setPurchaseNum(-1);
                        purchaseOrderMapper.updatePurchaseModel(models.get(i));
                    }

                }
                //插入 销货单入库表
                enterstockMapper.insertEnterStockOrder(procurementOrder1);
                enterstockMapper.insertEnterStockModel(procurementOrder1);
            }

        }
    }

    /**
     * wx公众号 查询采购入库 的 审核
     *
     * @param procurementWarehousingId 查询条件
     * @return 结果
     */
    @Override
    public List<Product> selectProcurementByIds(Long procurementWarehousingId) {
        return procurementOrderMapper.selectProcurementByIds(procurementWarehousingId);
    }

    /**
     * 插入 入库订单信息 PDA
     *
     * @param procurementOrder 入库订单信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertProcurementOrderPDA(ProcurementOrder procurementOrder) {
        //插入入库订单
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Long deptId = sysUser.getCompanyId();
//        Long deptId = 101L;
        procurementOrder.setDeptId(deptId);
        procurementOrder.setCreateBy(sysUser.getNickName());
//        procurementOrder.setCreateBy("ShiroUtils.getLoginName()");
        if (procurementOrder.getUserId() == null) {
            //查询供应商的绑定业务员
            Map<String, Object> map = new HashMap<>();
            map.put("deptId", sysUser.getCompanyId());
            map.put("companyId", procurementOrder.getSupplierId());
            CompanyOther companyOther = iCompanyOtherMapper.selectByCompanyIdAndDeptId(map);
            procurementOrder.setUserId(Long.valueOf(companyOther.getCustomerForPerson()));
//            procurementOrder.setUserId(ShiroUtils.getUserId());
////            procurementOrder.setUserId(101L);
        }

//        Long saleGoodsId = procurementOrder.getSaleGoodsId();
//        SaleGoodsOrder saleGoodsOrder = new SaleGoodsOrder();
//        saleGoodsOrder.setSaleGoodsId(saleGoodsId);
//        saleGoodsOrder.setSaleGoodsStatus("1");
//        saleGoodsOrder.setIsWarehousingOrder(1);
//        //判断是否为销货单入库，是则修改销货单信息
//        if (saleGoodsId != null) {
//            saleGoodsMapper.updateSaleGoodsOrder(saleGoodsOrder);
//        }
        if (procurementOrder.getProcurementModelList() != null) {
            List<ProcurementModel> procurementModelList = procurementOrder.getProcurementModelList();
            for (ProcurementModel procurementModel : procurementModelList) {
//                ProductModel productModel = productMapper.selectProductByModelCode(101L, procurementModel.getModelCode());
                ProductModel productModel = productMapper.selectProductByModelCode(sysUser.getCompanyId(), procurementModel.getModelCode());
                procurementModel.setProductId(productModel.getProductId());
                procurementModel.setModelNo(productModel.getModelNo());
                procurementModel.setNumMatch("是");
                procurementModel.setPackMatch("是");
                procurementModel.setDataMatch("是");
                procurementModel.setShippingMatch("是");
            }

            if (procurementOrder.getSaleGoodsId() != null) {
                BigDecimal taxAmount = new BigDecimal(0);
                BigDecimal purchaseAmount = new BigDecimal(0);
                for (ProcurementModel procurementModel : procurementModelList) {
//                    BigDecimal taxAmount = procurementOrder.getTaxAmount();
//                    BigDecimal purchaseAmount = procurementOrder.getPurchaseAmount();
                    BigDecimal purchasePrice = procurementModel.getPurchasePrice();
                    BigDecimal taxPrice = procurementModel.getTaxPrice();
                    int warehousingAmount = procurementModel.getWarehousingAmount();
                    BigDecimal num = new BigDecimal(Integer.toString(warehousingAmount));
                    procurementModel.setTaxTotal(taxPrice.multiply(num));
                    procurementModel.setPurchaseTotal(purchasePrice.multiply(num));
                    BigDecimal taxTotal = procurementModel.getTaxTotal();
                    BigDecimal purchaseTotal = procurementModel.getPurchaseTotal();

                    taxAmount = taxAmount.add(taxTotal);
                    purchaseAmount = purchaseAmount.add(purchaseTotal);
                }
                procurementOrder.setTaxAmount(taxAmount);
                procurementOrder.setPurchaseAmount(purchaseAmount);
            }

            procurementOrderMapper.insertProcurementOrder(procurementOrder);

//            try {
            //插入入库详细信息订单
            procurementOrderMapper.insertProcurementModelListPDA(procurementOrder);
//            } catch (Exception e) {
//                procurementOrderMapper.deleteProcurementOrder(procurementOrder.getProcurementWarehousingId());
//                e.printStackTrace();
//            }
            //添加审核订单
            Audit audit = new Audit();
            audit.setOrderId(procurementOrder.getProcurementWarehousingId());
            audit.setCompanyId(deptId);
            audit.setOrderType("2");
            audit.setAuditStatus("0");
            audit.setUserId(procurementOrder.getUserId());
            audit.setSupplierId(procurementOrder.getSupplierId());
            audit.setTaxAmount(procurementOrder.getTaxAmount());
            //订单编号
            audit.setOrderNum(procurementOrder.getProcurementWarehousingName());
            auditMapper.insertAudit(audit);

            //判断是否有该批次产品的产品资料 有修改，没有插入
            for (ProcurementModel procurementModel : procurementModelList) {
                Information information = new Information();
                information.setBatch(procurementModel.getBatch());
                information.setProductType(procurementModel.getProductType());
                information.setDeptId(deptId);
                information.setModelCode(procurementModel.getModelCode());

                Map<Object, Object> map = new HashMap<>();
                map.put("batch", procurementModel.getBatch());
                map.put("productType", procurementModel.getProductType());
                map.put("deptId", deptId);
                map.put("modelCode", procurementModel.getModelCode());
                //查询产品资料信息，有修改产品资料信息，否则插入产品资料信息
                Information information1 = informationMapper.selectInformationByMap(map);
                if (information1 != null) {
                    information.setModelCode(information1.getModelCode());
                    information.setFactoryInspectionName(information1.getFactoryInspectionName());
                    information.setFactoryInspectionAddress(information1.getFactoryInspectionAddress());
                    information.setCustomsName(information1.getCustomsName());
                    information.setCustomsAddress(information1.getCustomsAddress());
                    information.setCommodityName(information1.getCommodityName());
                    information.setCommodityAddress(information1.getCommodityAddress());
                    information.setDisinfectName(information1.getDisinfectName());
                    information.setDisinfectAddress(information1.getDisinfectAddress());
                    information.setNucleicAcidName(information1.getNucleicAcidName());
                    information.setNucleicAcidAddress(information1.getNucleicAcidAddress());
                    //                  information.setCreateBy("ShiroUtils.getLoginName()");
                    //                   information.setUpdateBy("ShiroUtils.getLoginName()");
                    information.setCreateBy(sysUser.getNickName());
                    information.setUpdateBy(sysUser.getNickName());
                    informationMapper.updateInformation(information);
                } else {
                    informationMapper.insertInformationCount(information);
                }
            }
        }
        return 1;
    }

    /**
     * 查询本公司下所有产品
     *
     * @param product 查询条件
     * @return 结果
     */
    @Override
    public List<ProductModel> selectProductLists(Product product) {
        return procurementOrderMapper.selectProductLists(product);
    }

    @Override
    public List<Integer> selectProductType(String productType) {
        return procurementOrderMapper.selectProductType(productType);
    }


    /**
     * 入库核验记录 查看信息 （增加退货数量）
     *
     * @return 结果
     */
    @Override
    public ProcurementOrder selectProcurementAndReturn(ProcurementOrder procurementOrders) {
        return procurementOrderMapper.selectProcurementAndReturn(procurementOrders);
    }

    /**
     * 通过订单编号以及公司主键，查询是否生成过相同订单编号的订单信息
     *
     * @param map 查询条件
     * @return 结果
     */
    @Override
    public ProcurementOrder selectProcurementByMap(Map<String, Object> map) {
        return procurementOrderMapper.selectProcurementByMap(map);
    }

    @Autowired
    private ProcurementStateHandlerFactory factory;

    @Override
    public int auditSale(ProcurementOrder procurementOrder) {
        // return factory.execute(procurementOrder.getProcurementWarehousingId(), procurementOrder.getProcurementStatus());
        // 根据订单Id获取原来的订单
        ProcurementOrder procurementOrder1 = procurementOrderMapper.selectProcurementById(procurementOrder.getProcurementWarehousingId());

        int num = 0;
        // 如果状态流转的订单的状态 !NULL&&!"",给查询到的订单一个审核时间
        if (procurementOrder.getProcurementStatus() != null && !procurementOrder.getProcurementStatus().equals("")) {
            procurementOrder1.setAuditTime(DateUtils.getNowDate());
        }

        if (procurementOrder.getProcurementStatus().equals("1")) {
            // 通过状态处理
            List<ProcurementModel> procurementModelList = procurementOrderMapper.selectProcurementModelById(procurementOrder.getProcurementWarehousingId());
            procurementOrder1.setProcurementStatus(procurementOrder.getProcurementStatus());
            procurementOrder1.setProcurementModelList(procurementModelList);
            calculation(procurementOrder1);
            num = procurementOrderMapper.updateProcurementOrder(procurementOrder1);
        } else if (procurementOrder.getProcurementStatus().equals("0")) {
            // 退回状态处理
            if ("1".equals(procurementOrder.getIsReturn())) {
                throw new RuntimeException("该订单已有退货,不允许退回审核");
            }

            procurementOrder1.setProcurementWarehousingId(procurementOrder.getProcurementWarehousingId());
            procurementOrder1.setAuditTime(DateUtils.getNowDate());
            procurementOrder1.setProcurementStatus(procurementOrder.getProcurementStatus());

            List<ProcurementModel> procurementModelList = procurementOrderMapper.selectProcurementModelById(procurementOrder.getProcurementWarehousingId());
            for (ProcurementModel procurementModel : procurementModelList) {
                procurementModel.setAllNum(-procurementModel.getAllNum());
            }
            for (ProcurementModel procurementModel : procurementModelList) {
                procurementModel.setWarehousingAmount(-procurementModel.getWarehousingAmount());
            }

            procurementOrder1.setProcurementModelList(procurementModelList);
            // if (procurementOrder1.getProcurementStatus().equals("1")) {
            //     calculation(procurementOrder1);
            // }
            calculation(procurementOrder1);

            procurementOrder1.setProcurementModelList(procurementModelList);
            procurementOrder1.setUpdateBy(SecurityUtils.getLoginUser().getNickName());
            procurementOrder1.setProcurementStatus(procurementOrder.getProcurementStatus());
            num = procurementOrderMapper.updateProcurementOrder(procurementOrder1);

            //若是销货单入库 则删除 销货单入库表
            if (procurementOrder.getSaleGoodsId() != null) {
                enterstockMapper.deleteEnterStockOrder(procurementOrder.getProcurementWarehousingId());
                enterstockMapper.deleteEnterStockModer(procurementOrder.getProcurementWarehousingId());
            }
        } else if (procurementOrder.getProcurementStatus().equals("2")) {
            procurementOrder1.setProcurementStatus(procurementOrder.getProcurementStatus());
            num = procurementOrderMapper.updateProcurementOrder(procurementOrder1);

        }
        // 同步InventoryAmount
        //List<ProcurementModel> procurementModelList = procurementOrderMapper.selectProcurementModelById(procurementOrder.getProcurementWarehousingId());
        //procurementModelList.forEach(model -> {
        //    InventoryAmount inventoryAmount = new InventoryAmount();
        //    inventoryAmount.setDeptId(model.getDeptId());
        //    inventoryAmount.setProductId(model.getProductId());
        //    inventoryAmount.setProductType(model.getProductType());
        //    inventoryAmount.setBatch(model.getBatch());
        //    List<InventoryAmount> inventoryAmounts = inventoryAmountMapper.selectInventorAmountList(inventoryAmount);
        //    if (inventoryAmounts.isEmpty()) { // 新增
        //        // 获取销售审核记录
        //        Audit audit = new Audit();
        //        audit.setOrderId(procurementOrder.getProcurementWarehousingId());
        //        inventoryAmount.setAuditId(auditMapper.selectAuditByOrderId(audit).getAuditId());

        //    } else { // 修改

        //    }

          //});
        return num;
    }

    @Autowired
    private InventoryAmountMapper inventoryAmountMapper;

    @Override
    public Long querypreviousId(Long procurementWarehousingId) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("procurementWarehousingId", procurementWarehousingId);
        params.put("deptId", SecurityUtils.getDeptId());
        return procurementOrderMapper.querypreviousId(params);
    }

    @Override
    public Long queryNextId(Long procurementWarehousingId) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("procurementWarehousingId", procurementWarehousingId);
        params.put("deptId", SecurityUtils.getDeptId());
        return procurementOrderMapper.queryNextId(params);
    }

    @Override
    public List<Map<String, Object>> pendingReview(Long deptID) {
        return procurementOrderMapper.pendingReview(deptID)
                .stream()
                .peek(item -> item.put("orderType", "采购入库订单"))
                .collect(Collectors.toList());
    }
}
